<?php

namespace app\bsadmin\controller;

use think\facade\Session;
use think\facade\Db;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;
use app\common\validate\Resume as ResumeValidate;
use app\bsadmin\model\Config as ConfigModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\ResumeExamineLog as ResumeExamineLogModel;
use app\common\model\ResumeEmploymentIntention as ResumeEmploymentIntentionModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\ResumeDownloaded as ResumeDownloadedModel;
use app\common\model\ResumeWorks as ResumeWorksModel;
use app\common\model\ResumeConsignment as ResumeConsignmentModel;
use app\common\model\ResumeCertificate as ResumeCertificateModel;
use app\common\model\ResumeEducationalExperience as ResumeEducationalExperienceModel;
use app\common\model\ResumeLanguageAbility as ResumeLanguageAbilityModel;
use app\common\model\ResumeProjectExperience as ResumeProjectExperienceModel;
use app\common\model\ResumeSelfDescription as ResumeSelfDescriptionModel;
use app\common\model\ResumeSpecialtyLabel as ResumeSpecialtyLabelModel;
use app\common\model\ResumeTrainingExperience as ResumeTrainingExperienceModel;
use app\common\model\ResumeWorkExperience as ResumeWorkExperienceModel;
use app\common\model\ResumeRefreshLog as ResumeRefreshLogModel;
use app\common\model\ResumeExtensionLog as ResumeExtensionLogModel;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserTimer as UserTimerModel;
use app\common\controller\Resume as ResumeController;
use app\common\controller\Jobs as JobsController;
use app\common\model\Feedback as FeedbackModel;
use app\bsadmin\model\Admin as AdminModel;
use app\common\model\Area as AreaModel;
use app\common\model\CompanyIndustry as CompanyIndustryModel;
use app\common\model\JobsCate as JobsCateModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\variable\MsgCode;
use Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Validate;

class Resume extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = $this->getSearchResumeWhere();
            $DataObj = ResumeModel::alias('resume')->where($where);
            if (!empty($G['jid']) && $G['jid']) {
                $DataObj->where('resume.id', 'NOTIN', function ($query) use ($G) {
                    $query->name('job_fair_resume')->where(['jid' => $G['jid']])->field('resume_id');
                });
            }
            $Data = $DataObj->join('user m', 'm.id = resume.uid')
                ->where(['edu.alias' => 'resume/educational_background'])
                ->where(['job_status.alias' => 'resume/job_status'])
                ->join('status_alias edu', 'edu.value=resume.educational_background')
                ->join('user_info uinfo', 'uinfo.uid = m.id')
                ->join('status_alias job_status', 'job_status.value = resume.job_status')
                ->join('api_app app', 'app.app_id = resume.app_id', 'LEFT')
                ->field('resume.*,m.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                    $v['top_time'] = $v['top'] && $v['top_time'] ? date('Y-m-d H:i:s', $v['top_time']) : '';
                    $v['recommend_time'] = $v['recommend'] && $v['recommend_time'] ? date('Y-m-d H:i:s', $v['recommend_time']) : '';
                    $v['nickname'] = base64_decode($v['nickname']);
                    $v['headimg'] = config('web.imgurl') . $v['headimg'];
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['friendly_time'] = friendly_time($v['refresh_time'], 'friendly');
                    $v['log'] = ResumeExamineLogModel::where(['resume_id' => $v->id])->limit(10)->order('id desc')->select();
                    $v->ResumeEmploymentIntention = ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id' => $v->id])
                        ->where(['nature_of_work.alias' => 'resume/nature_of_work'])
                        ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
                        ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=e.jobscate1')
                        ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=e.jobscate2')
                        ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=e.jobscate3')
                        ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work')
                        ->join('area province', 'province.id = e.job_area1', 'LEFT')
                        ->join('area city', 'city.id = e.job_area2', 'LEFT')
                        ->join('area area', 'area.id = e.job_area3', 'LEFT')
                        ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();
                    $v->resume_info = 0;
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $AdminModel = AdminModel::where(['status' => 1])->field('id,headimg,nickname,adviser_default')->select();
            $nature_of_work = StatusAliasModel::getCate("resume/nature_of_work");
            $job_status = StatusAliasModel::getCate("resume/job_status");
            View::assign('admin', $AdminModel);
            View::assign('nature_of_work', $nature_of_work);
            View::assign('job_status', $job_status);
            if (request()->isMobile())
                return View::fetch('index_mobile');
            return View::fetch();
        }
    }

    /**
     * 高级搜索
     * hhm
     * @return void
     */
    public function advancedSearch()
    {
        $S = input();
        $where = [];
        $wh = null;
        if (!empty($S['searchData'])) {
            foreach ($S['searchData'] as $v) {
                switch ($v['value']) {
                    case 'examine': //审核状态
                        //-1代表全部
                        if ($v['index'] != -1)
                            $where[] = ['resume.examine', '=', $v['index']];
                        break;
                    case 'resumeType': //简历类型
                        if ($v['index'] != -1)
                            $where[] = ['resume.' . $v['index'], '=', "1"];
                        break;
                    case 'natureOfWork': //工作性质
                        if ($v['index'] != -1)
                            //                            $where[]=['employment_intention.nature_of_work','=',$v['index']];
                            $wh = ['nature_of_work' => $v['index']];
                        break;
                    case 'jobStatus': //求职状态
                        if ($v['index'] != -1)
                            $where[] = ['resume.job_status', '=', $v['index']];
                        break;
                    case 'createTime': //创建时间
                        if ($v['index'] != -1)
                            $where[] = ['resume.create_time', '>=', getPastTimes($v['index'])];
                        break;
                    case 'refreshTime': //刷新时间
                        if ($v['index'] != -1)
                            $where[] = ['resume.refresh_time', '>=', getPastTimes($v['index'])];
                        break;
                    case 'integrity': //简历完整度
                        if ($v['index'] != -1)
                            $Index = explode(",", $v['index']);
                        $where[] = ['resume.progress', 'between', $Index];
                        break;
                    case 'source': //数据来源
                        if ($v['index'] != -1 && !empty($v['index']))
                            $where[] = ['app.app_id', '=', $v['index']];
                        if (empty($v['index']))
                            $where[] = ['resume.app_id', 'NULL', "NULL"];
                        break;
                }
            }
        }

        $subQuery = null;
        if (!empty($wh)) {
            $subQuery = Db::name('resume_employment_intention')
                ->where($wh)
                ->group("resume_id")
                ->column('resume_id');
        } else {
            $subQuery = Db::name('resume_employment_intention')
                ->group("resume_id")
                ->column('resume_id');
        }

        $DataObj = ResumeModel::alias('resume')->where($where);
        $Data = $DataObj->join('user m', 'm.id = resume.uid')
            ->whereIn('resume.id', $subQuery)
            ->where(['edu.alias' => 'resume/educational_background'])
            ->where(['job_status.alias' => 'resume/job_status'])
            ->join('status_alias edu', 'edu.value=resume.educational_background')
            ->join('user_info uinfo', 'uinfo.uid = m.id')
            ->join('status_alias job_status', 'job_status.value = resume.job_status')
            ->join('api_app app', 'app.app_id = resume.app_id', 'LEFT')
            ->field('resume.*,m.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status')
            ->order('id desc')->paginate($S['pageSize'])->each(function ($v) {
                $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                $v['top_time'] = $v['top'] && $v['top_time'] ? date('Y-m-d H:i:s', $v['top_time']) : '';
                $v['recommend_time'] = $v['recommend'] && $v['recommend_time'] ? date('Y-m-d H:i:s', $v['recommend_time']) : '';
                $v['nickname'] = base64_decode($v['nickname']);
                $v['headimg'] = config('web.imgurl') . $v['headimg'];
                $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                $v['friendly_time'] = friendly_time($v['refresh_time'], 'friendly');
                $v['log'] = ResumeExamineLogModel::where(['resume_id' => $v->id])->limit(10)->order('id desc')->select();
                $v->ResumeEmploymentIntention = ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id' => $v->id])
                    ->where(['nature_of_work.alias' => 'resume/nature_of_work'])
                    ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
                    ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=e.jobscate1')
                    ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=e.jobscate2')
                    ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=e.jobscate3')
                    ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work')
                    ->join('area province', 'province.id = e.job_area1', 'LEFT')
                    ->join('area city', 'city.id = e.job_area2', 'LEFT')
                    ->join('area area', 'area.id = e.job_area3', 'LEFT')
                    ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();
                $v->resume_info = 0;
                return $v;
            });
        if ($Data->items()) {
            return $this->ajaxReturn('', 0, $Data);
        } else {
            return $this->ajaxReturn('暂无数据~', -100);
        }
    }



    public function recycleBin()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = $this->getSearchResumeWhere();
            $DataObj = ResumeModel::onlyTrashed()->alias('resume')->where($where);
            if (!empty($G['jid']) && $G['jid']) {
                $DataObj->where('resume.id', 'NOTIN', function ($query) use ($G) {
                    $query->name('job_fair_resume')->where(['jid' => $G['jid']])->field('resume_id');
                });
            }
            $Data = $DataObj->join('user m', 'm.id = resume.uid')
                ->where(['edu.alias' => 'resume/educational_background'])
                ->where(['job_status.alias' => 'resume/job_status'])
                ->join('status_alias edu', 'edu.value=resume.educational_background')
                ->join('user_info uinfo', 'uinfo.uid = m.id')
                ->join('status_alias job_status', 'job_status.value = resume.job_status')
                ->join('api_app app', 'app.app_id = resume.app_id', 'LEFT')
                ->field('resume.*,m.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status')
                ->order('resume.delete_time desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                    $v['top_time'] = $v['top'] && $v['top_time'] ? date('Y-m-d H:i:s', $v['top_time']) : '';
                    $v['recommend_time'] = $v['recommend'] && $v['recommend_time'] ? date('Y-m-d H:i:s', $v['recommend_time']) : '';
                    $v['nickname'] = base64_decode($v['nickname']);
                    $v['headimg'] = config('web.imgurl') . $v['headimg'];
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['friendly_time'] = friendly_time($v['refresh_time'], 'friendly');
                    $v['log'] = ResumeExamineLogModel::where(['resume_id' => $v->id])->limit(10)->order('id desc')->select();
                    $v->ResumeEmploymentIntention = ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id' => $v->id])
                        ->where(['nature_of_work.alias' => 'resume/nature_of_work'])
                        ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
                        ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=e.jobscate1')
                        ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=e.jobscate2')
                        ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=e.jobscate3')
                        ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work')
                        ->join('area province', 'province.id = e.job_area1', 'LEFT')
                        ->join('area city', 'city.id = e.job_area2', 'LEFT')
                        ->join('area area', 'area.id = e.job_area3', 'LEFT')
                        ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();
                    $v->resume_info = 0;
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $AdminModel = AdminModel::where(['status' => 1])->field('id,headimg,nickname,adviser_default')->select();
            View::assign('admin', $AdminModel);
            return View::fetch();
        }
    }
    public function getSearchResumeWhere()
    {
        //        $G = request()->get();
        $G = input();
        $where = [];
        if ($G['key']) {
            switch ($G['search_type']) {
                case 'id':
                    $where[] = ['resume.id', '=', $G['key']];
                    break;
                case 'uid':
                    $where[] = ['resume.uid', '=', $G['key']];
                    break;
                case 'name':
                    $where[] = ['resume.name', 'like', '%' . $G['key'] . '%'];
                    break;
                case 'mobile':
                    $where[] = ['m.mobile', '=', $G['key']];
                    break;
                case 'email':
                    $where[] = ['m.email', '=', $G['key']];
                    break;
            }
        }
        if (!empty($G['progress']) && $G['progress'])
            $where[] = ['resume.progress', '>', $G['progress']];
        if (isset($G['examine']) && $G['examine'] != 'all')
            $where[] = ['resume.examine', '=', $G['examine']];
        if (!empty($G['refresh_time']) && strtotime($G['refresh_time']))
            $where[] = ['resume.refresh_time', '>', strtotime($G['refresh_time'] . ' 00:00:00')];
        return $where;
    }
    //    public function exportResume()
    //    {
    //        if (request()->isAjax()) {
    //            $G = request()->get();
    //            $where = $this->getSearchResumeWhere();
    //            $Field = [
    //                'resume.*',
    //                'm.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status',
    //                'app.app_name',
    //            ];
    //            $DataObj = ResumeModel::alias('resume')->where($where);
    //            if (!empty($G['jid']) && $G['jid']) {
    //                $DataObj->where('resume.id', 'NOTIN', function ($query) use ($G) {
    //                    $query->name('job_fair_resume')->where(['jid' => $G['jid']])->field('resume_id');
    //                });
    //            }
    //            $Data = $DataObj->join('user m', 'm.id = resume.uid')
    //                ->where(['edu.alias' => 'resume/educational_background'])
    //                ->where(['job_status.alias' => 'resume/job_status'])
    //                ->join('status_alias edu', 'edu.value=resume.educational_background')
    //                ->join('user_info uinfo', 'uinfo.uid = m.id')
    //                ->join('status_alias job_status', 'job_status.value = resume.job_status')
    //                ->join('api_app app', 'app.app_id = resume.app_id', 'LEFT')
    //                ->field(implode(',', $Field))
    //                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
    //                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
    //                    $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
    //                    $v->employment_intention = ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id' => $v->id])
    //                        ->where(['nature_of_work.alias' => 'resume/nature_of_work'])
    //                        ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
    //                        ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=e.jobscate1')
    //                        ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=e.jobscate2')
    //                        ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=e.jobscate3')
    //                        ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work')
    //                        ->join('area province', 'province.id = e.job_area1', 'LEFT')
    //                        ->join('area city', 'city.id = e.job_area2', 'LEFT')
    //                        ->join('area area', 'area.id = e.job_area3', 'LEFT')
    //                        ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();
    //
    //                    $v->educational_experience = ResumeEducationalExperienceModel::alias('edu')->where(['edu.resume_id' => $v->id])
    //                        ->where(['educational_background.alias' => 'resume/educational_background'])
    //                        ->join('status_alias educational_background', 'educational_background.value=edu.educational_background')
    //                        ->withAttr('start_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->withAttr('end_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->field('edu.school_name,edu.specialities,edu.start_time,edu.end_time,educational_background.title as educational_background')->select();
    //                    $v->work_experience = ResumeWorkExperienceModel::alias('work')->where(['work.resume_id' => $v->id])
    //                        ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=work.jobscate1')
    //                        ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=work.jobscate2')
    //                        ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=work.jobscate3')
    //                        ->withAttr('start_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->withAttr('end_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->field('work.company_name,work.job_content,work.job_title,work.start_time,work.end_time,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3')->select();
    //                    $v->training_experience = ResumeTrainingExperienceModel::where(['resume_id' => $v->id])
    //                        ->withAttr('start_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->withAttr('end_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->field('project_name,mechanism,training_content,start_time,end_time')->select();
    //                    $v->project_experience = ResumeProjectExperienceModel::where(['resume_id' => $v->id])
    //                        ->withAttr('start_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->withAttr('end_time', function ($v, $data) {
    //                            return date('Y-m', $v);
    //                        })->field('project_name,project_role,project_content,project_link,start_time,end_time')->select();
    //                    $v->certificate = ResumeCertificateModel::where(['resume_id' => $v->id])->column('certificate_name');
    //                    $v->language_ability = ResumeLanguageAbilityModel::where(['resume_id' => $v->id])->column('language_name');
    //                    $v->specialty_label = ResumeSpecialtyLabelModel::where(['resume_id' => $v->id])->column('specialty_label');
    //                    return $v;
    //                });
    //            if ($Data->items()) {
    //                $title = [
    //                    ['title' => 'ID', 'key' => 'id'],
    //                    ['title' => 'UID', 'key' => 'uid'],
    //                    ['title' => '姓名', 'key' => 'name'],
    //                    ['title' => '手机号', 'key' => 'mobile'],
    //                    ['title' => '求职状态', 'key' => 'job_status'],
    //                    ['title' => '求职意向', 'key' => 'employment_intention'],
    //                    ['title' => '审核状态', 'key' => 'examine'],
    //                    ['title' => '展示状态', 'key' => 'privacy'],
    //                    ['title' => '教育经历', 'key' => 'educational_experience'],
    //                    ['title' => '工作经历', 'key' => 'work_experience'],
    //                    ['title' => '培训经历', 'key' => 'training_experience'],
    //                    ['title' => '项目经历', 'key' => 'project_experience'],
    //                    ['title' => '获得证书', 'key' => 'certificate'],
    //                    ['title' => '语言能力', 'key' => 'language_ability'],
    //                    ['title' => '特长标签', 'key' => 'specialty_label'],
    //                    ['title' => '年龄', 'key' => 'age'],
    //                    ['title' => '性别', 'key' => 'sex'],
    //                    ['title' => '学历', 'key' => 'educational_background'],
    //                    ['title' => '经验(年)', 'key' => 'work_experience_time'],
    //                    ['title' => '来源', 'key' => 'app_name'],
    //                    ['title' => '创建时间', 'key' => 'create_time'],
    //                    ['title' => '刷新时间', 'key' => 'refresh_time']
    //                ];
    //                $spreadsheet = new Spreadsheet;
    //                $sheet = $spreadsheet->getActiveSheet();
    //
    //                //表头
    //                //设置单元格内容
    //                $titCol = 'A';
    //                foreach ($title as $key => $v) {
    //                    // 单元格内容写入
    //                    $sheet->setCellValue($titCol . '1', $v['title']);
    //                    $titCol++;
    //                }
    //                $row = 2;
    //                foreach ($Data->items() as $item) {
    //                    $dataCol = 'A';
    //                    foreach ($title as $key => $v) {
    //                        switch ($v['key']) {
    //                            case 'employment_intention':
    //                                $employment_intention = [];
    //                                foreach ($item->employment_intention as $obj) {
    //                                    $salary = '面议';
    //                                    if ($obj->salary_min > 0)
    //                                        $salary = $obj->salary_min . '-' . $obj->salary_max;
    //                                    $employment_intention[] = $obj->jobs_cate3 . '·' . ($obj->industry ? $obj->industry : '行业不限') . '·' . ($obj->area_city ? $obj->area_city . $obj->area_area : '地区不限') . '·' . $salary;
    //                                }
    //                                if (!empty($employment_intention))
    //                                    $sheet->setCellValue($dataCol . $row, implode("\n", $employment_intention));
    //                                break;
    //                            case 'educational_experience':
    //                                $educational_experience = [];
    //                                foreach ($item->educational_experience as $obj) {
    //                                    $educational_experience[] = $obj->educational_background . '·' . $obj->school_name . '·' . $obj->specialities . '·' . $obj->start_time . '~' . $obj->end_time;
    //                                }
    //                                if (!empty($educational_experience))
    //                                    $sheet->setCellValue($dataCol . $row, implode("\n", $educational_experience));
    //                                break;
    //                            case 'work_experience':
    //                                $work_experience = [];
    //                                foreach ($item->work_experience as $obj) {
    //                                    $work_experience[] = $obj->company_name . '·' . $obj->jobs_cate3 . '·' . $obj->job_title . '·' . $obj->start_time . '~' . $obj->end_time;
    //                                }
    //                                if (!empty($work_experience))
    //                                    $sheet->setCellValue($dataCol . $row, implode("\n", $work_experience));
    //                                break;
    //                            case 'training_experience':
    //                                $training_experience = [];
    //                                foreach ($item->training_experience as $obj) {
    //                                    $training_experience[] = $obj->mechanism . '·' . $obj->project_name . '·' . $obj->start_time . '~' . $obj->end_time;
    //                                }
    //                                if (!empty($training_experience))
    //                                    $sheet->setCellValue($dataCol . $row, implode("\n", $training_experience));
    //                                break;
    //                            case 'project_experience':
    //                                $project_experience = [];
    //                                foreach ($item->project_experience as $obj) {
    //                                    $project_experience[] = $obj->project_name . '·' . $obj->project_role . '·' . $obj->project_link . '·' . $obj->start_time . '~' . $obj->end_time;
    //                                }
    //                                if (!empty($project_experience))
    //                                    $sheet->setCellValue($dataCol . $row, implode("\n", $project_experience));
    //                                break;
    //                            case 'certificate':
    //                                if ($item->certificate)
    //                                    $sheet->setCellValue($dataCol . $row, implode('·', $item->certificate));
    //                                break;
    //                            case 'language_ability':
    //                                if ($item->language_ability)
    //                                    $sheet->setCellValue($dataCol . $row, implode('·', $item->language_ability));
    //                                break;
    //                            case 'specialty_label':
    //                                if ($item->specialty_label)
    //                                    $sheet->setCellValue($dataCol . $row, implode('·', $item->specialty_label));
    //                                break;
    //                            case 'examine':
    //                                switch ($item->examine) {
    //                                    case 0:
    //                                        $sheet->setCellValue($dataCol . $row, '未审核');
    //                                        break;
    //                                    case 1:
    //                                        $sheet->setCellValue($dataCol . $row, '已审核');
    //                                        break;
    //                                    case 2:
    //                                        $sheet->setCellValue($dataCol . $row, '未通过');
    //                                        break;
    //                                }
    //                                break;
    //                            case 'privacy':
    //                                switch ($item->privacy) {
    //                                    case 0:
    //                                        $sheet->setCellValue($dataCol . $row, '未展示');
    //                                        break;
    //                                    case 1:
    //                                        $sheet->setCellValue($dataCol . $row, '展示中');
    //                                        break;
    //                                }
    //                                break;
    //                            case 'sex':
    //                                switch ($item->sex) {
    //                                    case 1:
    //                                        $sheet->setCellValue($dataCol . $row, '男');
    //                                        break;
    //                                    case 2:
    //                                        $sheet->setCellValue($dataCol . $row, '女');
    //                                        break;
    //                                }
    //                                break;
    //                            case 'work_experience_time':
    //                                $sheet->setCellValue($dataCol . $row, date('Y') - date('Y', $item->work_experience_time));
    //                                break;
    //                            case 'age':
    //                                $sheet->setCellValue($dataCol . $row, date('Y') - date('Y', $item->age));
    //                                break;
    //                            default:
    //                                $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
    //                                break;
    //                        }
    //                        $dataCol++;
    //                    }
    //                    $row++;
    //                }
    //                $filename = 'output/resume/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
    //                if (!file_exists(dirname($filename)))
    //                    mkdir(dirname($filename), 0777, true);
    //                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    //                $writer->save($filename);
    //                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
    //            } else {
    //                return $this->ajaxReturn('暂无数据~', -100);
    //            }
    //        }
    //    }
    public function exportResume()
    {
        if (request()->isAjax()) {
            $G = request()->post();
            if (empty($G['selectNum']))
                return $this->ajaxReturn('请选择需要导出的简历', -100);
            $where = $this->getSearchResumeWhere();
            $Field = [
                'resume.*',
                'm.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status',
                'app.app_name',
            ];
            $DataObj = ResumeModel::alias('resume')->where($where);
            if (!empty($G['jid']) && $G['jid']) {
                $DataObj->where('resume.id', 'NOTIN', function ($query) use ($G) {
                    $query->name('job_fair_resume')->where(['jid' => $G['jid']])->field('resume_id');
                });
            }
            $Data = $DataObj->join('user m', 'm.id = resume.uid')
                ->where(['edu.alias' => 'resume/educational_background'])
                ->where(['job_status.alias' => 'resume/job_status'])
                ->join('status_alias edu', 'edu.value=resume.educational_background')
                ->join('user_info uinfo', 'uinfo.uid = m.id')
                ->join('status_alias job_status', 'job_status.value = resume.job_status')
                ->join('api_app app', 'app.app_id = resume.app_id', 'LEFT')
                ->field(implode(',', $Field))
                //                ->order('id desc')->paginate($G['pageSize'])
                ->whereIn('m.id', $G['selectNum'])->select()->each(function ($v) {
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                    $v->employment_intention = ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id' => $v->id])
                        ->where(['nature_of_work.alias' => 'resume/nature_of_work'])
                        ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
                        ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=e.jobscate1')
                        ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=e.jobscate2')
                        ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=e.jobscate3')
                        ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work')
                        ->join('area province', 'province.id = e.job_area1', 'LEFT')
                        ->join('area city', 'city.id = e.job_area2', 'LEFT')
                        ->join('area area', 'area.id = e.job_area3', 'LEFT')
                        ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();

                    $v->educational_experience = ResumeEducationalExperienceModel::alias('edu')->where(['edu.resume_id' => $v->id])
                        ->where(['educational_background.alias' => 'resume/educational_background'])
                        ->join('status_alias educational_background', 'educational_background.value=edu.educational_background')
                        ->withAttr('start_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->withAttr('end_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->field('edu.school_name,edu.specialities,edu.start_time,edu.end_time,educational_background.title as educational_background')->select();
                    $v->work_experience = ResumeWorkExperienceModel::alias('work')->where(['work.resume_id' => $v->id])
                        ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=work.jobscate1')
                        ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=work.jobscate2')
                        ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=work.jobscate3')
                        ->withAttr('start_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->withAttr('end_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->field('work.company_name,work.job_content,work.job_title,work.start_time,work.end_time,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3')->select();
                    $v->training_experience = ResumeTrainingExperienceModel::where(['resume_id' => $v->id])
                        ->withAttr('start_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->withAttr('end_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->field('project_name,mechanism,training_content,start_time,end_time')->select();
                    $v->project_experience = ResumeProjectExperienceModel::where(['resume_id' => $v->id])
                        ->withAttr('start_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->withAttr('end_time', function ($v, $data) {
                            return date('Y-m', $v);
                        })->field('project_name,project_role,project_content,project_link,start_time,end_time')->select();
                    $v->certificate = ResumeCertificateModel::where(['resume_id' => $v->id])->column('certificate_name');
                    $v->language_ability = ResumeLanguageAbilityModel::where(['resume_id' => $v->id])->column('language_name');
                    $v->specialty_label = ResumeSpecialtyLabelModel::where(['resume_id' => $v->id])->column('specialty_label');
                    return $v;
                });
            if ($Data) {
                $title = [
                    ['title' => 'ID', 'key' => 'id'],
                    ['title' => 'UID', 'key' => 'uid'],
                    ['title' => '姓名', 'key' => 'name'],
                    ['title' => '手机号', 'key' => 'mobile'],
                    ['title' => '求职状态', 'key' => 'job_status'],
                    ['title' => '求职意向', 'key' => 'employment_intention'],
                    ['title' => '审核状态', 'key' => 'examine'],
                    ['title' => '展示状态', 'key' => 'privacy'],
                    ['title' => '教育经历', 'key' => 'educational_experience'],
                    ['title' => '工作经历', 'key' => 'work_experience'],
                    ['title' => '培训经历', 'key' => 'training_experience'],
                    ['title' => '项目经历', 'key' => 'project_experience'],
                    ['title' => '获得证书', 'key' => 'certificate'],
                    ['title' => '语言能力', 'key' => 'language_ability'],
                    ['title' => '特长标签', 'key' => 'specialty_label'],
                    ['title' => '年龄', 'key' => 'age'],
                    ['title' => '性别', 'key' => 'sex'],
                    ['title' => '学历', 'key' => 'educational_background'],
                    ['title' => '经验(年)', 'key' => 'work_experience_time'],
                    ['title' => '来源', 'key' => 'app_name'],
                    ['title' => '创建时间', 'key' => 'create_time'],
                    ['title' => '刷新时间', 'key' => 'refresh_time']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();

                //表头
                //设置单元格内容
                $titCol = 'A';
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '1', $v['title']);
                    $titCol++;
                }
                $row = 2;
                foreach ($Data as $item) {
                    $dataCol = 'A';
                    foreach ($title as $key => $v) {
                        switch ($v['key']) {
                            case 'employment_intention':
                                $employment_intention = [];
                                foreach ($item->employment_intention as $obj) {
                                    $salary = '面议';
                                    if ($obj->salary_min > 0)
                                        $salary = $obj->salary_min . '-' . $obj->salary_max;
                                    $employment_intention[] = $obj->jobs_cate3 . '·' . ($obj->industry ? $obj->industry : '行业不限') . '·' . ($obj->area_city ? $obj->area_city . $obj->area_area : '地区不限') . '·' . $salary;
                                }
                                if (!empty($employment_intention))
                                    $sheet->setCellValue($dataCol . $row, implode("\n", $employment_intention));
                                break;
                            case 'educational_experience':
                                $educational_experience = [];
                                foreach ($item->educational_experience as $obj) {
                                    $educational_experience[] = $obj->educational_background . '·' . $obj->school_name . '·' . $obj->specialities . '·' . $obj->start_time . '~' . $obj->end_time;
                                }
                                if (!empty($educational_experience))
                                    $sheet->setCellValue($dataCol . $row, implode("\n", $educational_experience));
                                break;
                            case 'work_experience':
                                $work_experience = [];
                                foreach ($item->work_experience as $obj) {
                                    $work_experience[] = $obj->company_name . '·' . $obj->jobs_cate3 . '·' . $obj->job_title . '·' . $obj->start_time . '~' . $obj->end_time;
                                }
                                if (!empty($work_experience))
                                    $sheet->setCellValue($dataCol . $row, implode("\n", $work_experience));
                                break;
                            case 'training_experience':
                                $training_experience = [];
                                foreach ($item->training_experience as $obj) {
                                    $training_experience[] = $obj->mechanism . '·' . $obj->project_name . '·' . $obj->start_time . '~' . $obj->end_time;
                                }
                                if (!empty($training_experience))
                                    $sheet->setCellValue($dataCol . $row, implode("\n", $training_experience));
                                break;
                            case 'project_experience':
                                $project_experience = [];
                                foreach ($item->project_experience as $obj) {
                                    $project_experience[] = $obj->project_name . '·' . $obj->project_role . '·' . $obj->project_link . '·' . $obj->start_time . '~' . $obj->end_time;
                                }
                                if (!empty($project_experience))
                                    $sheet->setCellValue($dataCol . $row, implode("\n", $project_experience));
                                break;
                            case 'certificate':
                                if ($item->certificate)
                                    $sheet->setCellValue($dataCol . $row, implode('·', $item->certificate));
                                break;
                            case 'language_ability':
                                if ($item->language_ability)
                                    $sheet->setCellValue($dataCol . $row, implode('·', $item->language_ability));
                                break;
                            case 'specialty_label':
                                if ($item->specialty_label)
                                    $sheet->setCellValue($dataCol . $row, implode('·', $item->specialty_label));
                                break;
                            case 'examine':
                                switch ($item->examine) {
                                    case 0:
                                        $sheet->setCellValue($dataCol . $row, '未审核');
                                        break;
                                    case 1:
                                        $sheet->setCellValue($dataCol . $row, '已审核');
                                        break;
                                    case 2:
                                        $sheet->setCellValue($dataCol . $row, '未通过');
                                        break;
                                }
                                break;
                            case 'privacy':
                                switch ($item->privacy) {
                                    case 0:
                                        $sheet->setCellValue($dataCol . $row, '未展示');
                                        break;
                                    case 1:
                                        $sheet->setCellValue($dataCol . $row, '展示中');
                                        break;
                                }
                                break;
                            case 'sex':
                                switch ($item->sex) {
                                    case 1:
                                        $sheet->setCellValue($dataCol . $row, '男');
                                        break;
                                    case 2:
                                        $sheet->setCellValue($dataCol . $row, '女');
                                        break;
                                }
                                break;
                            case 'work_experience_time':
                                $sheet->setCellValue($dataCol . $row, date('Y') - date('Y', $item->work_experience_time));
                                break;
                            case 'age':
                                $sheet->setCellValue($dataCol . $row, date('Y') - date('Y', $item->age));
                                break;
                            default:
                                $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
                                break;
                        }
                        $dataCol++;
                    }
                    $row++;
                }
                $filename = 'output/resume/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        }
    }



    public function getFind($id)
    {
        $D = [
            'is_admin'    =>  1
        ];
        $Find = ResumeController::getResumeInfo($id, $D);
        if ($Find) {
            /*记录访客*/
            View::assign('Find', $Find);
            View::assign('webtitle', $Find['name'] . '的简历');
        } else {
            return redirect('/system/maintenance?msg=不存在该简历');
        }
        return View::fetch();
    }
    public function setResumeExamine()
    {
        $D = request()->post();
        $id = $D['id'];
        $status = $D['status'];
        $msg = $D['msg'];
        $ResumeModel = ResumeModel::where(['id' => $id])->find();
        if ($status == 1) {
            $ResumeModel->examine = 1;
            $ResumeExamineLogModel = new ResumeExamineLogModel;
            $ResumeExamineLogModel->resume_id = $ResumeModel->id;
            $ResumeExamineLogModel->status = 1;
            $ResumeExamineLogModel->msg = '审核通过';
            $ResumeExamineLogModel->admin_uid = Session::get('AdminUser.uid');
            $ResumeExamineLogModel->ip = request()->ip();
            $PushTaskModel = null;
            if (!empty($D['notice'])) {
                $PushTaskModel = new PushTaskModel;
                $PushTaskModel->event       =   'ResumeExamine';
                $PushTaskModel->uid         =   $ResumeModel->uid;
                $PushData = $ResumeModel->toArray();
                $PushData['hi_text'] = '恭喜您';
                $PushData['status'] = '已通过';
                $PushData['msg'] = '通过';
                $PushData['time'] = date('Y-m-d H:i:s');
                $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
            }
            // 启动事务
            Db::startTrans();
            try {
                $ResumeModel->save();
                if ($PushTaskModel) $PushTaskModel->save();
                $ResumeExamineLogModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $ResumeModel->examine = 2;
            $ResumeExamineLogModel = new ResumeExamineLogModel;
            $ResumeExamineLogModel->resume_id = $ResumeModel->id;
            $ResumeExamineLogModel->status = 2;
            $ResumeExamineLogModel->msg = $msg;
            $ResumeExamineLogModel->admin_uid = Session::get('AdminUser.uid');
            $ResumeExamineLogModel->ip = request()->ip();
            $PushTaskModel = null;
            if (!empty($D['notice'])) {
                $PushTaskModel = new PushTaskModel;
                $PushTaskModel->event       =   'ResumeExamine';
                $PushTaskModel->uid         =   $ResumeModel->uid;
                $PushData = $ResumeModel->toArray();
                $PushData['hi_text'] = '很遗憾';
                $PushData['status'] = '未通过';
                $PushData['msg'] = $msg;
                $PushData['time'] = date('Y-m-d H:i:s');
                $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
            }
            // 启动事务
            Db::startTrans();
            try {
                $ResumeModel->save();
                if ($PushTaskModel) $PushTaskModel->save();
                $ResumeExamineLogModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        }
    }
    /**
     * 获取简历信息
     */
    public function getResumeInfo($id)
    {
        $Find = ResumeController::getResumeInfo($id, ['is_admin' => 1]);
        if ($Find) {
            return $this->ajaxReturn('', 0, $Find);
        } else {
            return $this->ajaxReturn('无此企业数据', -100);
        }
    }
    public function refreshResume($id)
    {
        $ResumeModel = ResumeModel::where(['id' => $id])->find();
        $ResumeModel->refresh_time = time();
        if ($ResumeModel->save()) {
            return $this->ajaxReturn('已刷新', 0, ['refresh_time' => date('Y-m-d H:i', $ResumeModel->refresh_time)]);
        } else {
            return $this->ajaxReturn('刷新失败，请重试', -100);
        }
    }
    public function setPrivacy()
    {
        $D = request()->post();
        if (empty($D['id'])) {
            return $this->ajaxReturn('简历不存在', -100);
        }
        $ResumeModel = ResumeModel::where(['id' => $D['id']])->find();
        if (!isset($D['privacy'])) {
            return $this->ajaxReturn('参数错误', -100);
        }
        $ResumeModel->privacy = $D['privacy'];
        $ResumeModel->save();
        return $this->ajaxReturn('ok', MsgCode::$success, $ResumeModel);
    }
    public function setResumeTop()
    {
        $D = request()->post();
        if (empty($D['id'])) return $this->ajaxReturn('简历不存在', -100);
        $ResumeModel = ResumeModel::where(['id' => $D['id']])->find();
        $top = 0;
        if (!empty($D['top'])) $top = 1;
        $accumulation = 0;
        if (!empty($D['accumulation'])) $accumulation = 1;
        $ResumeModel->top = $top;
        $end_time = time();
        if ($top) {
            if ($accumulation) {
                if ($ResumeModel->top_time) {
                    $end_time = $ResumeModel->top_time + 3600 * 24 * intval($D['top']);
                } else {
                    $end_time = time() + 3600 * 24 * intval($D['top']);
                }
            } else {
                $end_time = time() + 3600 * 24 * intval($D['top']);
            }
        }
        $ResumeModel->top_time = $end_time;
        $ResumeExtensionLogModel = new ResumeExtensionLogModel;
        $ResumeExtensionLogModel->uid = $ResumeModel->uid;
        $ResumeExtensionLogModel->resume_id = $ResumeModel->id;
        $ResumeExtensionLogModel->vid = 0;
        $ResumeExtensionLogModel->type = 8;
        $ResumeExtensionLogModel->value = intval($D['top']);
        $ResumeExtensionLogModel->start_time = time();
        $ResumeExtensionLogModel->end_time = $end_time;
        $ResumeExtensionLogModel->admin_uid = Session::get('AdminUser.uid');
        // 启动事务
        Db::startTrans();
        try {
            $ResumeModel->save();
            $ResumeExtensionLogModel->save();
            // 提交事务
            Db::commit();
            $ResumeModel->top_time = date('Y-m-d H:i:s', $ResumeModel->top_time);
            return $this->ajaxReturn('', 0, $ResumeModel);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function setResumeRecommend()
    {
        $D = request()->post();
        if (empty($D['id'])) return $this->ajaxReturn('职位不存在', -100);
        $ResumeModel = ResumeModel::where(['id' => $D['id']])->find();
        $recommend = 0;
        if (!empty($D['recommend'])) $recommend = 1;
        $accumulation = 0;
        if (!empty($D['accumulation'])) $accumulation = 1;
        $ResumeModel->recommend = $recommend;
        $end_time = time();
        if ($recommend) {
            if ($accumulation) {
                if ($ResumeModel->recommend_time) {
                    $end_time = $ResumeModel->recommend_time + 3600 * 24 * intval($D['recommend']);
                } else {
                    $end_time = time() + 3600 * 24 * intval($D['recommend']);
                }
            } else {
                $end_time = time() + 3600 * 24 * intval($D['recommend']);
            }
        }
        $ResumeModel->recommend_time = $end_time;
        $ResumeExtensionLogModel = new ResumeExtensionLogModel;
        $ResumeExtensionLogModel->uid = $ResumeModel->uid;
        $ResumeExtensionLogModel->resume_id = $ResumeModel->id;
        $ResumeExtensionLogModel->vid = 0;
        $ResumeExtensionLogModel->type = 13;
        $ResumeExtensionLogModel->value = intval($D['recommend']);
        $ResumeExtensionLogModel->start_time = time();
        $ResumeExtensionLogModel->end_time = $end_time;
        $ResumeExtensionLogModel->admin_uid = Session::get('AdminUser.uid');
        // 启动事务
        Db::startTrans();
        try {
            $ResumeModel->save();
            $ResumeExtensionLogModel->save();
            // 提交事务
            Db::commit();
            $ResumeModel->recommend_time = date('Y-m-d H:i:s', $ResumeModel->recommend_time);
            return $this->ajaxReturn('', 0, $ResumeModel);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function editResume($id)
    {
        if (request()->isAjax()) {
            $D = request()->post();
            $D['uid'] = $id;
            /*
            *  调用公共保存简历方法
            *  app\common\controller\Resume
            */
            // dd($D['employment_intention']);
            foreach ($D['employment_intention'] as $key => $value) {
                $expected_salary = [$value['min_salary'], $value['max_salary']];
                if (count($expected_salary) < 2) {
                    return parent::ajaxReturn('简历信息不完整：求职意向薪资范围未填写(第' . $key . '份)');
                }
                $expected_salary[0] = floor(intval($expected_salary[0]) / 100) * 100;
                $expected_salary[1] = floor(intval($expected_salary[1]) / 100) * 100;
                sort($expected_salary);

                $D['employment_intention'][$key]['expected_salary'] = $expected_salary;
            }
            return ResumeController::saveResume($D);
        } else {
            View::assign('Find', ResumeController::getResumeInfoAll($id));
            return View::fetch('add_resume');
        }
    }
    public function setResumeDelete($id)
    {
        $ResumeModel = ResumeModel::find($id);
        if ($ResumeModel) {
            $ResumeModel->top = 0;
            $ResumeModel->recommend = 0;
            $ResumeModel->save();
            if ($ResumeModel->delete()) {
                return $this->ajaxReturn();
            } else {
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $ResumeModel = ResumeModel::onlyTrashed()->find($id);
            if ($ResumeModel) {
                if (empty(request()->get('force'))) {
                    if ($ResumeModel->restore()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                } else {
                    if ($ResumeModel->force()->delete()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                }
            }
        }
        return $this->ajaxReturn('简历不存在', -100);
    }
    /**
     * 删除简历经历
     */
    public function delExperience($type, $id, $uid, $resume_id)
    {
        if (request()->isAjax() && request()->isGet()) {
            $D = [
                'id'        =>  $id,
                'type'      =>  $type,
                'uid'       =>  $uid,
                'resume_id' =>  $resume_id
            ];
            /*
            *  调用公共删除简历经历方法
            *  app\common\controller\Resume
            */
            return ResumeController::delExperience($D);
        }
    }
    public function addResume()
    {
        if (request()->isAjax()) {
            $D = request()->post();
            /**
             * 简历基本信息验证
             */
            try {
                validate(ResumeValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(), -100);
            }
            $required_field = config('xy_resume.required_field');
            if (in_array('self_description', $required_field) && empty($D['self_description']))
                return $this->ajaxReturn('自我描述不能为空', -100);
            if (in_array('educational_experience', $required_field) && empty($D['educational_experience']))
                return $this->ajaxReturn('教育经历不能为空', -100);
            if (in_array('work_experience', $required_field) && empty($D['work_experience']))
                return $this->ajaxReturn('工作经历不能为空', -100);
            if (in_array('training_experience', $required_field) && empty($D['training_experience']))
                return $this->ajaxReturn('培训经历不能为空', -100);
            if (in_array('project_experience', $required_field) && empty($D['project_experience']))
                return $this->ajaxReturn('项目经历不能为空', -100);
            if (in_array('certificate', $required_field) && empty($D['certificate']))
                return $this->ajaxReturn('证书不能为空', -100);
            if (in_array('language_ability', $required_field) && empty($D['language_ability']))
                return $this->ajaxReturn('语言能力不能为空', -100);
            if (in_array('specialty_label', $required_field) && empty($D['specialty_label']))
                return $this->ajaxReturn('特长不能为空', -100);

            $Validate = new Validate;
            if (!$Validate->regex($D['mobile'], 'mobile'))
                return $this->ajaxReturn('手机号不正确', -100);
            /**
             * 用户
             */
            $UserModel = UserModel::where(['mobile' => $D['mobile']])->find();
            $UserInfoModel = null;
            $UserTimerModel = null;
            if ($UserModel) {
                if (ResumeModel::where(['uid' => $UserModel->id])->count())
                    return $this->ajaxReturn('该手机号已创建简历', -100);
            } else {
                $passHash = Str::random(4);
                $UserModel = new UserModel;
                $UserModel->mobile = $D['mobile'];
                $UserModel->email = $D['email'];
                $UserModel->password_hash = $passHash;
                if ($D['password']) {
                    $UserModel->password = UserModel::getPassword($passHash, $D['password']);
                } else {
                    $UserModel->password = UserModel::getPassword($passHash, $D['mobile']);
                }
                /**
                 * 用户信息
                 */
                $UserInfoModel = new UserInfoModel;
                $UserInfoModel->nickname = base64_encode(config('basic.nickname_header') . substr_replace($D['mobile'], '****', 3, 4));
                $UserInfoModel->headimg = config('xy_default_avatar.user');
                $UserInfoModel->role_type = 0;
                $UserTimerModel = new UserTimerModel;
                $UserTimerModel->online_time = time();
                $UserTimerModel->online_ip = request()->ip();
                $UserTimerModel->online_devices = substr(request()->header('user-agent'), 0, 200);
                $UserTimerModel->login_time = time();
                $UserTimerModel->login_ip = request()->ip();
                $UserTimerModel->login_devices = substr(request()->header('user-agent'), 0, 200);
                $UserTimerModel->register_time = time();
                $UserTimerModel->register_ip = request()->ip();
                $UserTimerModel->register_devices = substr(request()->header('user-agent'), 0, 200);
            }
            $ResumeModel = new ResumeModel;
            $ResumeModel->refresh_time          =   time();
            $ResumeModel->name                  =   $D['name'];
            $ResumeModel->sex                   =   $D['sex'];
            $ResumeModel->headimg_status        =   $D['headimg_status'];
            $ResumeModel->age                   =   round($D['age'] / 1000);
            $ResumeModel->educational_background =   $D['educational_background'];
            $ResumeModel->work_experience_time  =   round($D['work_experience_time'] / 1000);
            if (!empty($D['specialities']))
                $ResumeModel->specialities          =   $D['specialities'];
            $ResumeModel->residence             =   $D['residence'];
            $ResumeModel->native_place          =   $D['native_place'];
            $ResumeModel->is_marry              =   $D['is_marry'];
            $ResumeModel->contact_qq            =   $D['contact_qq'];
            $ResumeModel->contact_wechat        =   $D['contact_wechat'];
            $ResumeModel->job_status            =   empty($D['job_status']) ? 4 : $D['job_status'];
            if (config('xy_resume.edit_resume_view_status'))
                $ResumeModel->examine = 0;

            if ($ResumeModel) {
                $ResumeSelfDescriptionModel = ResumeSelfDescriptionModel::where(['resume_id' => $ResumeModel->id])->find();
                if (!$ResumeSelfDescriptionModel)
                    $ResumeSelfDescriptionModel = new ResumeSelfDescriptionModel;
            } else {
                $ResumeSelfDescriptionModel = new ResumeSelfDescriptionModel;
            }
            $ResumeSelfDescriptionModel->self_description = $D['self_description'];

            $ResumeEmploymentIntentionModel = new ResumeEmploymentIntentionModel;
            $ResumeEmploymentIntentionList = [];
            if (!empty($D['employment_intention'])) {
                $ResumeEmploymentIntentionDefault = 0;
                foreach ($D['employment_intention'] as $k => $v) {
                    if (count($ResumeEmploymentIntentionList) >= 3)
                        break;
                    $ResumeEmploymentIntentionList[$k] = [
                        'nature_of_work'            =>  $v['nature_of_work'],
                        'industry_id'               =>  $v['industry_id'],
                        'jobscate1'                 =>  $v['jobscate'][0],
                        'jobscate2'                 =>  $v['jobscate'][1],
                        'jobscate3'                 =>  $v['jobscate'][2],
                        'expected_salary'           =>  $v['expected_salary'][0],
                        'expected_salary'           =>  $v['expected_salary'][1],
                        'default'                   =>  0,
                    ];
                    if (!empty($v['job_area']) && count($v['job_area']) == 3) {
                        $ResumeEmploymentIntentionList[$k]['job_area1'] = $v['job_area'][0];
                        $ResumeEmploymentIntentionList[$k]['job_area2'] = $v['job_area'][1];
                        $ResumeEmploymentIntentionList[$k]['job_area3'] = $v['job_area'][2];
                    }
                    if ($v['id'])
                        $ResumeEmploymentIntentionList[$k]['id'] = $v['id'];
                    if (!empty($v['default']) && $v['default'] && !$ResumeEmploymentIntentionDefault) {
                        $ResumeEmploymentIntentionList[$k]['default'] = 1;
                        $ResumeEmploymentIntentionDefault = 1;
                    }
                }
            }
            if (empty($ResumeEmploymentIntentionList))
                return $this->ajaxReturn('求职意向不能为空', -100);
            /*教育经历*/
            $ResumeEducationalExperienceModel = new ResumeEducationalExperienceModel;
            $EducationalExperienceList = [];
            if (!empty($D['educational_experience'])) {
                foreach ($D['educational_experience'] as $k => $v) {
                    $EducationalExperienceList[$k] = [
                        'school_name'               =>  $v['school_name'],
                        'specialities'              =>  $v['specialities'],
                        'educational_background'    =>  $v['educational_background'],
                        'start_time'                =>  round($v['start_time'] / 1000),
                        'end_time'                  =>  round($v['end_time'] / 1000)
                    ];
                    if ($v['id'])
                        $EducationalExperienceList[$k]['id'] = $v['id'];
                }
            }
            /*工作经历*/
            $ResumeWorkExperienceModel = new ResumeWorkExperienceModel;
            $ResumeWorkExperienceList = [];
            if (!empty($D['work_experience'])) {
                foreach ($D['work_experience'] as $k => $v) {
                    $ResumeWorkExperienceList[$k] = [
                        'company_name'              =>  $v['company_name'],
                        'jobscate1'                 =>  $v['jobscate'][0],
                        'jobscate2'                 =>  $v['jobscate'][1],
                        'jobscate3'                 =>  $v['jobscate'][2],
                        'job_content'               =>  $v['job_content'],
                        'job_title'                 =>  $v['job_title'],
                        'start_time'                =>  round($v['start_time'] / 1000),
                        'end_time'                  =>  round($v['end_time'] / 1000)
                    ];
                    if ($v['id'])
                        $ResumeWorkExperienceList[$k]['id'] = $v['id'];
                }
            }
            /*培训经历*/
            $ResumeTrainingExperienceModel = new ResumeTrainingExperienceModel;
            $ResumeTrainingExperienceList = [];
            if (!empty($D['training_experience'])) {
                foreach ($D['training_experience'] as $k => $v) {
                    $ResumeTrainingExperienceList[$k] = [
                        'project_name'              =>  $v['project_name'],
                        'mechanism'                 =>  $v['mechanism'],
                        'training_content'          =>  $v['training_content'],
                        'start_time'                =>  round($v['start_time'] / 1000),
                        'end_time'                  =>  round($v['end_time'] / 1000)
                    ];
                    if ($v['id'])
                        $ResumeTrainingExperienceList[$k]['id'] = $v['id'];
                }
            }
            $ResumeProjectExperienceModel = new ResumeProjectExperienceModel;
            $ResumeProjectExperienceList = [];
            if (!empty($D['project_experience'])) {
                foreach ($D['project_experience'] as $k => $v) {
                    $ResumeProjectExperienceList[$k] = [
                        'project_name'              =>  $v['project_name'],
                        'project_role'              =>  $v['project_role'],
                        'project_content'           =>  $v['project_content'],
                        'project_link'              =>  $v['project_link'],
                        'start_time'                =>  round($v['start_time'] / 1000),
                        'end_time'                  =>  round($v['end_time'] / 1000)
                    ];
                    if ($v['id'])
                        $ResumeProjectExperienceList[$k]['id'] = $v['id'];
                }
            }
            /*获得证书*/
            $ResumeCertificateModel = new ResumeCertificateModel;
            $CertificateList = [];
            if (!empty($D['certificate'])) {
                foreach ($D['certificate'] as $k => $v) {
                    if (!$v['id'])
                        $CertificateList[]['certificate_name'] = $v['certificate_name'];
                }
            }
            /*语言能力*/
            $ResumeLanguageAbilityModel = new ResumeLanguageAbilityModel;
            $LanguageAbilityList = [];
            if (!empty($D['language_ability'])) {
                foreach ($D['language_ability'] as $k => $v) {
                    if (!$v['id'])
                        $LanguageAbilityList[]['language_name'] = $v['language_name'];
                }
            }
            /*特长*/
            $ResumeSpecialtyLabelModel = new ResumeSpecialtyLabelModel;
            $SpecialtyLabelList = [];
            if (!empty($D['specialty_label'])) {
                foreach ($D['specialty_label'] as $k => $v) {
                    if (!$v['id'])
                        $SpecialtyLabelList[]['specialty_label'] = $v['specialty_label'];
                }
            }
            $PushTaskModel = new PushTaskModel;
            $PushTaskModel->event       =   'SystemWarning';
            // 启动事务
            Db::startTrans();
            try {
                if ($UserInfoModel) $UserModel->save();
                $UserInfoModel->uid = $UserModel->id;
                $UserTimerModel->uid = $UserModel->id;
                if ($UserInfoModel) $UserInfoModel->save();
                if ($UserTimerModel) $UserTimerModel->save();
                $ResumeModel->uid = $UserModel->id;
                $ResumeModel->save();
                $ResumeSelfDescriptionModel->resume_id = $ResumeModel->id;
                $ResumeSelfDescriptionModel->save();
                if (!empty($ResumeEmploymentIntentionList)) {
                    array_walk($ResumeEmploymentIntentionList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeEmploymentIntentionModel->saveAll($ResumeEmploymentIntentionList);
                }
                if (!empty($EducationalExperienceList)) {
                    array_walk($EducationalExperienceList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeEducationalExperienceModel->saveAll($EducationalExperienceList);
                }
                if (!empty($ResumeWorkExperienceList)) {
                    array_walk($ResumeWorkExperienceList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeWorkExperienceModel->saveAll($ResumeWorkExperienceList);
                }
                if (!empty($ResumeTrainingExperienceList)) {
                    array_walk($ResumeTrainingExperienceList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeTrainingExperienceModel->saveAll($ResumeTrainingExperienceList);
                }
                if (!empty($ResumeProjectExperienceList)) {
                    array_walk($ResumeProjectExperienceList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeProjectExperienceModel->saveAll($ResumeProjectExperienceList);
                }
                if (!empty($CertificateList)) {
                    array_walk($CertificateList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeCertificateModel->saveAll($CertificateList);
                }
                if (!empty($LanguageAbilityList)) {
                    array_walk($LanguageAbilityList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeLanguageAbilityModel->saveAll($LanguageAbilityList);
                }
                if (!empty($SpecialtyLabelList)) {
                    array_walk($SpecialtyLabelList, function (&$v, $k) use ($ResumeModel) {
                        $v['resume_id'] = $ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeSpecialtyLabelModel->saveAll($SpecialtyLabelList);
                }
                $PushData = [
                    'tpl'       => 'resume_examine',
                    'level'     => '审核简历',
                    'range'     => '后台',
                    'time'      => date('Y-m-d H:i:s'),
                    //                    'msg'       => '审核简历ID:' . $ResumeModel->id
                    'msg'       => "您有新的简历需要审核，用户:{$ResumeModel->name}(UID:{$ResumeModel->uid})提交了简历(简历ID:{$ResumeModel->id})，等待您的审核。"

                ];
                $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
                $PushTaskModel->save();
                // 提交事务
                Db::commit();
                ResumeController::calculationResumeProgress($ResumeModel->id);
                ResumeController::delResumeFile($ResumeModel->id);
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            return View::fetch();
        }
    }
    public function downloadResumeLog()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'company_id':
                        $where[] = ['d.company_id', '=', $G['key']];
                        break;
                    case 'resume_id':
                        $where[] = ['d.resume_id', '=', $G['key']];
                        break;
                    case 'company_name':
                        $where[] = ['company.title', 'like', '%' . $G['key'] . '%'];
                        break;
                }
            }
            $Data = ResumeDownloadedModel::alias('d')
                ->where($where)
                ->where(['edu.alias' => 'resume/educational_background'])
                ->join('company company', 'company.id=d.company_id')
                ->join('resume resume', 'resume.id=d.resume_id')
                ->join('status_alias edu', 'edu.value=resume.educational_background')
                ->order('d.id desc')
                ->field('d.*,resume.name,resume.sex,resume.age,resume.work_experience_time,edu.title as educational_background,company.title as company_name,company.stitle as scompany_name')->paginate($G['pageSize'])
                ->each(function ($item, $key) {
                    return $item;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            return View::fetch();
        }
    }
    public function works()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'resume_id':
                        $where[] = ['w.resume_id', '=', $G['key']];
                        break;
                }
            }
            if ($G['status'] != 'all') {
                $where[] = ['w.status', '=', $G['status']];
            }
            $Data = ResumeWorksModel::alias('w')->where($where)
                ->join('resume resume', 'resume.id = w.resume_id')
                ->field('w.*,resume.name')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['url'] = config('web.imgurl') . $v['path'];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('works_mobile');
            return View::fetch();
        }
    }
    public function setResumeWorksStatus($id, $status)
    {
        $ResumeWorksModel = ResumeWorksModel::where(['id' => $id])->find();
        $ResumeWorksModel->status = $status;
        if ($ResumeWorksModel->save()) {
            return $this->ajaxReturn('已保存', 0, ['update_time' => date('Y-m-d H:i:s')]);
        } else {
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function setAdviser($id, $adviser_id)
    {
        $ResumeModel = ResumeModel::where(['id' => $id])->find();
        $ResumeModel->adviser_id = $adviser_id;
        if ($ResumeModel->save()) {
            return $this->ajaxReturn('已设置');
        } else {
            return $this->ajaxReturn('设置失败，请重试', -100);
        }
    }
    public function setting()
    {
        $Data = ConfigModel::getList([['ctype', 'in', ['xy_resume', 'xy_company', 'xy_default_avatar']]]);
        View::assign('Data', $Data);
        View::assign('ctype', 'xy_resume');
        return View::fetch('setting/resume');
    }
    public function consignment()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'resume_id':
                        $where[] = ['rc.resume_id', '=', $G['key']];
                        break;
                    case 'uid':
                        $where[] = ['resume.uid', '=', $G['key']];
                        break;
                    case 'name':
                        $where[] = ['resume.name', 'like', '%' . $G['key'] . '%'];
                        break;
                }
            }
            $Data = ResumeConsignmentModel::alias('rc')->where($where)
                ->where(['edu.alias' => 'resume/educational_background'])
                ->join('resume resume', 'resume.id=rc.resume_id')
                ->join('user m', 'm.id = resume.uid')
                ->join('status_alias edu', 'edu.value=resume.educational_background')
                ->join('user_info uinfo', 'uinfo.uid = m.id')
                ->field('rc.*,resume.name,resume.age,resume.sex,resume.work_experience_time,uinfo.nickname,uinfo.headimg,edu.title as educational_background')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['nickname'] = base64_decode($v['nickname']);
                    $v['headimg'] = config('web.imgurl') . $v['headimg'];
                    $v['cancel_time'] = $v['cancel_time'] ? date('Y-m-d H:i:s', $v['cancel_time']) : '';
                    $v['start_time'] = $v['start_time'] ? date('Y-m-d', $v['start_time']) : '';
                    $v['end_time'] = $v['end_time'] ? date('Y-m-d', $v['end_time']) : '';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            return View::fetch();
        }
    }
    public function cancelConsignment($id)
    {
        $ResumeConsignmentModel = ResumeConsignmentModel::where(['id' => $id])->find();
        $ResumeConsignmentModel->status = 0;
        $ResumeConsignmentModel->cancel_time = time();
        if ($ResumeConsignmentModel->save()) {
            return $this->ajaxReturn();
        } else {
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function matching($resume_id)
    {
        if (request()->isAjax() && request()->isGet()) {
            $G = request()->get();
            $Resume = ResumeModel::where(['id' => $resume_id])->field('id,uid')->find();
            $G['uid'] = $Resume->uid;
            $G['resume_id'] = $resume_id;
            $Data = JobsController::getJobsList($G);
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $Find = ResumeController::getResumeInfo($resume_id, ['is_admin' => 1]);
            $ResumeEmploymentIntention = ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id' => $resume_id, 'e.default' => 1])
                ->where(['nature_of_work.alias' => 'resume/nature_of_work'])
                ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
                ->join('jobs_cate jobs_cate1', 'jobs_cate1.id=e.jobscate1')
                ->join('jobs_cate jobs_cate2', 'jobs_cate2.id=e.jobscate2')
                ->join('jobs_cate jobs_cate3', 'jobs_cate3.id=e.jobscate3')
                ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work')
                ->join('area province', 'province.id = e.job_area1', 'LEFT')
                ->join('area city', 'city.id = e.job_area2', 'LEFT')
                ->join('area area', 'area.id = e.job_area3', 'LEFT')
                ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area1,e.job_area2,e.job_area3,e.jobscate3,e.nature_of_work,nature_of_work.title as nature_of_work_title,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->find();
            View::assign('Resume', $Find);
            View::assign('ResumeEmploymentIntention', $ResumeEmploymentIntention);
            return View::fetch();
        }
    }
    /**
     * 投递简历
     */
    public function deliveryResume($resume_id, $id)
    {
        if (request()->isAjax() && request()->isGet()) {
            $Resume = ResumeModel::where(['id' => $resume_id])->field('id,uid')->find();
            $G = request()->get();
            $D = [
                'id'        =>  $id,
                'confirm'   =>  empty($G['confirm']) ? 0 : $G['confirm'],
                'uid'       =>  $Resume->uid
            ];
            /*
            *  调用公共投递简历方法
            *  app\common\controller\Resume
            */
            return ResumeController::deliveryResume($D, 1);
        }
    }
    public function resume_complaints()
    {
        View::assign('type', 6);
        return View::fetch('feedback/index');
    }

    public function importResume()
    {
        if (request()->isAjax()) {
            // 获取json格式的简历
            $resume = request()->post();
            try {
                $resumeData = $this->checkResume($resume);
                $this->insertResume($resumeData);
                return $this->ajaxReturn();
            } catch (\Throwable $ex) {
                return $this->ajaxReturn($ex->getMessage(), -100);
            }
        }
        return View::fetch('import');
    }

    public function verifyResume()
    {
        $resume = input('post.');
        try {
            if (empty($resume)) {
                throw new Exception('参数错误!');
            }
            // 检验有效性
            $this->checkResume($resume);
        } catch (\Throwable $ex) {
            return $this->ajaxReturn($ex->getMessage(), -1, ['line' => $ex->getLine()]);
        }
        return $this->ajaxReturn('success', 0);
    }

    public function insertResume($userData)
    {
        try {
            // 启动事务
            Db::startTrans();
            // 创建用户
            $user = UserModel::create($userData);
            // 创建用户信息
            $userInfoData = $userData['user_info'];
            $userInfoData['uid'] = $user->id;
            UserInfoModel::create($userInfoData);
            // 创建用户时间线
            $userTimerData = $userData['user_timer'];
            $userTimerData['uid'] = $user->id;
            UserTimerModel::create($userTimerData);
            // 创建简历主表
            $resumeData = $userData['resume'];
            $resumeData['uid'] = $user->id;
            $resume = ResumeModel::create($resumeData);
            // 创建自我描述
            $resumeData['resume_id'] = $resume->id;
            ResumeSelfDescriptionModel::create($resumeData);
            // 创建求职意向
            $resumeEmpIntData = $resumeData['employment_intention'];
            for ($i = 0; $i < count($resumeEmpIntData); $i++) {
                $item = $resumeEmpIntData[$i];
                $item['resume_id'] = $resume->id;
                ResumeEmploymentIntentionModel::create($item);
            }
            // 创建教育经历
            $resumeEduExpData = $resumeData['educational_experience'];
            for ($i = 0; $i < count($resumeEduExpData); $i++) {
                $item = $resumeEduExpData[$i];
                $item['resume_id'] = $resume->id;
                ResumeEducationalExperienceModel::create($item);
            }
            // 创建培训经历
            $resumeTrainingExpData = $resumeData['training_experience'];
            for ($i = 0; $i < count($resumeTrainingExpData); $i++) {
                $item = $resumeTrainingExpData[$i];
                $item['resume_id'] = $resume->id;
                ResumeTrainingExperienceModel::create($item);
            }
            // 创建工作经历
            $resumeWorkExpData = $resumeData['work_experience'];
            for ($i = 0; $i < count($resumeWorkExpData); $i++) {
                $item = $resumeWorkExpData[$i];
                $item['resume_id'] = $resume->id;
                ResumeWorkExperienceModel::create($item);
            }
            // 创建项目经历
            $resumeProjectExpData = $resumeData['project_experience'];
            for ($i = 0; $i < count($resumeProjectExpData); $i++) {
                $item = $resumeProjectExpData[$i];
                $item['resume_id'] = $resume->id;
                ResumeProjectExperienceModel::create($item);
            }

            // 创建证书
            $resumeCertsData = $resumeData['certificate'];
            for ($i = 0; $i < count($resumeCertsData); $i++) {
                $item['certificate_name'] = $resumeCertsData[$i];
                $item['resume_id'] = $resume->id;
                ResumeCertificateModel::create($item);
            }
            // 创建语言能力
            $resumeCertsData = $resumeData['language_ability'];
            for ($i = 0; $i < count($resumeCertsData); $i++) {
                $item['language_name'] = $resumeCertsData[$i];
                $item['resume_id'] = $resume->id;
                ResumeLanguageAbilityModel::create($item);
            }
            // 创建标签
            $resumeLabelsData = $resumeData['specialty_label'];
            for ($i = 0; $i < count($resumeLabelsData); $i++) {
                $item['specialty_label'] = $resumeLabelsData[$i];
                $item['resume_id'] = $resume->id;
                ResumeSpecialtyLabelModel::create($item);
            }
            Db::commit();
            // 计算简历完整度
            ResumeController::calculationResumeProgress($resume->id);
        } catch (\Throwable $ex) {
            Db::rollback();
            throw $ex;
        }
    }

    private function checkResume(array $resume)
    {
        // 初始化简历
        $resumeData = [];
        $resumeEmpIntData = [];

        #region 空值检测
        if (empty($resume['name'])) {
            throw new Exception('简历姓名不能为空');
        }
        if (empty($resume['sex'])) {
            throw new Exception('简历姓名不能为空');
        }
        if (empty($resume['age'])) {
            throw new Exception('简历姓名不能为空');
        }
        if (empty($resume['educational_background'])) {
            throw new Exception('最高学历不能为空');
        }
        if (empty($resume['work_experience_time'])) {
            throw new Exception('简历参加工作时间不能为空');
        }
        if (empty($resume['job_status'])) {
            throw new Exception('简历求职状态不能为空');
        }
        if (empty($resume['mobile'])) {
            throw new Exception('简历手机号不能为空');
        }
        if (empty($resume['employment_intention'])) {
            throw new Exception('简历求职意向不能为空(至少包含一项)');
        }
        // 检测求职意向是否有效
        if (!is_array($resume['employment_intention'])) {
            throw new Exception('求职意向格式不符合要求');
        }
        #endregion

        // 判断用户是否存在
        $userExist = UserModel::where('mobile', $resume['mobile'])->find();
        if ($userExist) {
            throw new Exception('用户已存在，无法导入');
        }

        #region 有效性校验
        // 获取字典
        $eduLevelList = StatusAliasModel::where('alias', 'resume/educational_background')->column('value', 'title');
        $jobStatuslList = StatusAliasModel::where('alias', 'resume/job_status')->column('value', 'title');

        // $politicallList = StatusAliasModel::where('alias', 'resume/political_affiliation')->column('value', 'title');

        if ($resume['sex'] !== 1 && $resume['sex'] !== 2) {
            throw new Exception('性别格式不符合要求');
        }
        if (!is_int($resume['age'])) {
            throw new Exception('出生年月格式不符合要求');
        }
        if (!is_int($resume['work_experience_time'])) {
            throw new Exception('参加工作时间格式不符合要求');
        }
        if (empty($eduLevelList[$resume['educational_background']])) {
            throw new Exception('最高学历的格式不符合要求');
        }

        if (empty($jobStatuslList[$resume['job_status']])) {
            throw new Exception('求职状态的格式不符合要求');
        }
        // 居住地区
        if (empty($resume['residenceArea1']) || empty($resume['residenceArea2'])) {
            throw new Exception('简历居住地不能为空');
        }
        $residenceArea1 = AreaModel::where('title', $resume['residenceArea1'])->where('pid', 0)->value('id');
        if (empty($residenceArea1)) {
            throw new Exception('简历居住地的格式不符合要求(一级地区不存在或不匹配)');
        }
        $residenceArea2 = AreaModel::where('pid', $residenceArea1)->where('title', $resume['residenceArea2'])->value('id');
        if (empty($residenceArea2)) {
            throw new Exception('简历居住地的格式不符合要求(二级地区不存在或不匹配)');
        }
        // 户籍地区
        if (empty($resume['nativePlaceArea1']) || empty($resume['nativePlaceArea2'])) {
            throw new Exception('简历籍贯地区不能为空');
        }
        $nativePlaceArea1 = AreaModel::where('title', $resume['nativePlaceArea1'])->where('pid', 0)->value('id');
        if (empty($nativePlaceArea1)) {
            throw new Exception('简历籍贯地区的格式不符合要求(一级地区不存在或不匹配)');
        }
        $nativePlaceArea2 = AreaModel::where('pid', $nativePlaceArea1)->where('title', $resume['nativePlaceArea2'])->value('id');
        if (!$nativePlaceArea2) {
            throw new Exception('简历籍贯地区的格式不符合要求(二级地区不存在或不匹配)');
        }
        #endregion
        // 检测并生成求职意向数据
        $resumeEmpIntData = $this->checkResumeEmpInt($resume['employment_intention']);
        // 检测并生成教育经历
        $resumeEduExpData = $this->checkResumeEduExp($resume['educational_experience'] ?? [], $eduLevelList);
        // 检测并生成培训经历
        $resumeTrainingExpData = $this->checkResumeTrainingExp($resume['training_experience'] ?? []);
        // 检测并生成工作经历
        $resumeWorkExpData = $this->checkResumeWorkExp($resume['work_experience'] ?? []);
        // 检测并生成工作经历
        $resumeProjectExpData = $this->checkResumeProjectExp($resume['project_experience'] ?? []);
        // 检测并生成获得证书
        $resumeCerts = $resume['certificate'] ?? [];
        // 检测并生成语言能力
        $resumeLangs = $resume['language_ability'] ?? [];
        // 检测并生成特长标签
        $resumeLables = $resume['specialty_label'] ?? [];
        // 创建简历数据
        $resumeData = [
            'name' => $resume['name'],
            'age' => $resume['age'],
            'sex' => $resume['sex'],
            'specialities' => $resume['specialities'] ?? null,
            'residence' => $residenceArea2,
            'native_place' => $nativePlaceArea2,
            'educational_background' => $eduLevelList[$resume['educational_background']],
            'work_experience_time' => $resume['work_experience_time'],
            'job_status' => $jobStatuslList[$resume['job_status']],
            'mobile' => $resume['mobile'],
            'self_description' => $resume['self_description'] ?? '',
            'refresh_time' => time(),
            'employment_intention' => $resumeEmpIntData,
            'educational_experience' => $resumeEduExpData,
            'training_experience' => $resumeTrainingExpData,
            'project_experience' => $resumeProjectExpData,
            'work_experience' => $resumeWorkExpData,
            'certificate' => $resumeCerts,
            'language_ability' => $resumeLangs,
            'specialty_label' => $resumeLables
        ];
        // 创建用户数据
        $userData = [
            'mobile' => $resume['mobile'],
            'password_hash' => Str::random(4),
            /* 用户信息 */
            'user_info' => [
                'nickname' => base64_encode(config('basic.nickname_header') . substr_replace($resume['mobile'], '****', 3, 4)),
                'headimg' => config('xy_default_avatar.user'),
                'role_type' => 0
            ],
            /* 用户时间线 */
            'user_timer' => [
                'online_time' => time(),
                'login_time' => time(),
                'register_time' => time(),
                'online_ip' => request()->ip(),
                'login_ip' => request()->ip(),
                'register_ip' => request()->ip(),
                'online_devices' => substr(request()->header('user-agent'), 0, 200),
                'login_devices' => substr(request()->header('user-agent'), 0, 200),
                'register_devices' => substr(request()->header('user-agent'), 0, 200)
            ],
            'resume' => $resumeData
        ];
        return $userData;
    }

    private function checkResumeEmpInt($empInt)
    {
        if (count($empInt) < 1) {
            throw new Exception('求职意向至少包含一个！');
        }
        $natureList = StatusAliasModel::where('alias', 'resume/nature_of_work')->column('value', 'title');
        $result = [];
        for ($i = 0; $i < count($empInt) && $i < 3; $i++) {
            $nature = null;
            // 工作性质
            $nature = $natureList[$empInt[$i]['nature_of_work']] ?? 1;

            // 期望薪资
            if (!is_int($empInt[$i]['salary_min']) || !is_int($empInt[$i]['salary_max'])) {
                continue;
            }
            // $empInt[$i]['salary_min'] < 0 ? 0 : $empInt[$i]['salary_min'];
            // $empInt[$i]['salary_min'] > 100 ? 100 : $empInt[$i]['salary_min'];
            // $empInt[$i]['salary_max'] < 0 ? 100 : $empInt[$i]['salary_max'];
            // $empInt[$i]['salary_max'] > 100 ? 100 : $empInt[$i]['salary_max'];

            // 工作地区
            if (empty($empInt[$i]['job_area1'])) {
                continue;
            }

            $anyArea = $empInt[$i]['job_area1'] == '地区不限';

            if (empty($empInt[$i]['job_area2']) || empty($empInt[$i]['job_area3'])) {
                if (!$anyArea) {
                    continue;
                }
            }
            // 如果是地区不限则不匹配地区，反之则匹配
            if (!$anyArea) {
                $area1 = AreaModel::where('title', $empInt[$i]['job_area1'])->where('pid', 0)->value('id');
                if (empty($area1)) {
                    continue;
                }
                $area2 = AreaModel::where('title', $empInt[$i]['job_area2'])->where('pid', $area1)->value('id');
                if (empty($area2)) {
                    continue;
                }
                $area3 = AreaModel::where('title', $empInt[$i]['job_area3'])->where('pid', $area2)->value('id');
                if (empty($area3)) {
                    continue;
                }
            } else {
                $area1 = null;
                $area2 = null;
                $area3 = null;
            }

            // 期望行业
            $industry = CompanyIndustryModel::where('title', $empInt[$i]['industry_id'])->value('id');
            if (empty($industry)) {
                continue;
            }
            // 职位类型
            if (empty($empInt[$i]['jobscate1']) || empty($empInt[$i]['jobscate2']) || empty($empInt[$i]['jobscate3'])) {
                continue;
            }
            $cate1 = JobsCateModel::where('title', $empInt[$i]['jobscate1'])->where('pid', 0)->value('id');
            if (empty($cate1)) {
                continue;
            }
            $cate2 = JobsCateModel::where('title', $empInt[$i]['jobscate2'])->where('pid', $cate1)->value('id');
            if (empty($cate2)) {
                continue;
            }
            $cate3 = JobsCateModel::where('title', $empInt[$i]['jobscate3'])->where('pid', $cate2)->value('id');
            if (empty($cate3)) {
                continue;
            }

            $empInt[$i]['salary_min'] = $empInt[$i]['salary_min'] < 0 ? 0 : $empInt[$i]['salary_min'];
            $empInt[$i]['salary_max'] = $empInt[$i]['salary_max'] < 0 ? 0 : $empInt[$i]['salary_max'];
            $salary = [$empInt[$i]['salary_min'], $empInt[$i]['salary_max']];
            sort($salary);
            $data = [
                'nature_of_work' => $nature,
                'job_area1' => $area1,
                'job_area2' => $area2,
                'job_area3' => $area3,
                'industry_id' => $industry,
                'jobscate1' => $cate1,
                'jobscate2' => $cate2,
                'jobscate3' => $cate3,
                'salary_min' => $salary[0] * 1000,
                'salary_max' => $salary[1] * 1000
            ];
            $result[] = $data;
        }
        if (empty($result)) {
            throw new Exception('求职意向不符合格式要求，请对照说明书仔细检查');
        }
        return $result;
    }

    private function checkResumeEduExp($eduExp, $eduLevelList)
    {
        $result = [];
        for ($i = 0; $i < count($eduExp); $i++) {
            if (empty($eduExp[$i]['educational_background'])) {
                continue;
            }
            if (empty($eduExp[$i]['school_name'])) {
                continue;
            }
            if (empty($eduExp[$i]['specialities'])) {
                continue;
            }
            if (empty($eduExp[$i]['start_time']) || empty($eduExp[$i]['end_time'])) {
                continue;
            }
            if (!is_int($eduExp[$i]['start_time']) || !is_int($eduExp[$i]['end_time'])) {
                continue;
            }
            $eduLevel = $eduLevelList[$eduExp[$i]['educational_background']];
            if (empty($eduLevel)) {
                continue;
            }
            $result[] = [
                'school_name' => $eduExp[$i]['school_name'],
                'specialities' => $eduExp[$i]['specialities'],
                'educational_background' => $eduLevel,
                'start_time' => $eduExp[$i]['start_time'],
                'end_time' => $eduExp[$i]['end_time']
            ];
        }
        return $result;
    }

    private function checkResumeTrainingExp($trainingExp)
    {
        $result = [];
        for ($i = 0; $i < count($trainingExp); $i++) {
            if (empty($trainingExp[$i]['mechanism'])) {
                continue;
            }
            if (empty($trainingExp[$i]['project_name'])) {
                continue;
            }
            if (empty($trainingExp[$i]['start_time']) || empty($trainingExp[$i]['end_time'])) {
                continue;
            }
            if (!is_int($trainingExp[$i]['start_time']) || !is_int($trainingExp[$i]['end_time'])) {
                continue;
            }
            $result[] = [
                'mechanism' => $trainingExp[$i]['mechanism'],
                'project_name' => $trainingExp[$i]['project_name'],
                'training_content' => $trainingExp[$i]['training_content'] ?? '',
                'start_time' => $trainingExp[$i]['start_time'],
                'end_time' => $trainingExp[$i]['end_time']
            ];
        }
        return $result;
    }

    private function checkResumeWorkExp($workExp)
    {
        $result = [];
        for ($i = 0; $i < count($workExp); $i++) {
            if (empty($workExp[$i]['company_name'])) {
                continue;
            }
            if (empty($workExp[$i]['job_title'])) {
                continue;
            }
            if (empty($workExp[$i]['start_time']) || empty($workExp[$i]['end_time'])) {
                continue;
            }
            if (!is_int($workExp[$i]['start_time']) || !is_int($workExp[$i]['end_time'])) {
                continue;
            }

            if (empty($workExp[$i]['jobscate1']) || empty($workExp[$i]['jobscate2']) || empty($workExp[$i]['jobscate3'])) {
                continue;
            }
            $cate1 = JobsCateModel::where('title', $workExp[$i]['jobscate1'])->where('pid', 0)->value('id');
            if (empty($cate1)) {
                continue;
            }
            $cate2 = JobsCateModel::where('title', $workExp[$i]['jobscate2'])->where('pid', $cate1)->value('id');
            if (empty($cate2)) {
                continue;
            }
            $cate3 = JobsCateModel::where('title', $workExp[$i]['jobscate3'])->where('pid', $cate2)->value('id');
            if (empty($cate3)) {
                continue;
            }

            $result[] = [
                'company_name' => $workExp[$i]['company_name'],
                'job_title' => $workExp[$i]['job_title'],
                'job_content' => $workExp[$i]['job_content'] ?? '',
                'jobscate1' => $cate1,
                'jobscate2' => $cate2,
                'jobscate3' => $cate3,
                'start_time' => $workExp[$i]['start_time'],
                'end_time' => $workExp[$i]['end_time']
            ];
        }
        return $result;
    }

    private function checkResumeProjectExp($projectExp)
    {
        $result = [];
        for ($i = 0; $i < count($projectExp); $i++) {
            if (empty($projectExp[$i]['project_name'])) {
                continue;
            }
            if (empty($projectExp[$i]['project_role'])) {
                continue;
            }
            if (empty($projectExp[$i]['start_time']) || empty($projectExp[$i]['end_time'])) {
                continue;
            }
            if (!is_int($projectExp[$i]['start_time']) || !is_int($projectExp[$i]['end_time'])) {
                continue;
            }
            $result[] = [
                'project_name' => $projectExp[$i]['project_name'],
                'project_role' => $projectExp[$i]['project_role'],
                'project_link' => $projectExp[$i]['project_link'] ?? null,
                'project_content' => $projectExp[$i]['project_content'] ?? '',
                'start_time' => $projectExp[$i]['start_time'],
                'end_time' => $projectExp[$i]['end_time']
            ];
        }
        return $result;
    }
}
